package com.launch.carmanager.common.rx;


import com.launch.carmanager.common.Constants;
import com.launch.carmanager.common.base.BaseResponse;
import com.launch.carmanager.common.expection.ApiException;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by ganquan on 2019/3/28 10:23
 */
@SuppressWarnings("unchecked")
public class ApiTransformer<T> implements Observable.Transformer<BaseResponse<T>, T> {

    @Override
    public Observable<T> call(Observable<BaseResponse<T>> tObservable) {
        return tObservable.compose(new SchedulerTransformer<BaseResponse<T>>()).flatMap(new Func1<BaseResponse<T>, Observable<T>>() {
            @Override
            public Observable<T> call(BaseResponse r) {

                if (r.getErrcode() == Constants.ErrorCode.SUCCESS) {
                    return Observable.just((T) r.getData());
                } else {
                    // 处理API异常
                    return Observable.error(new ApiException(r.getMsg(), r.getErrcode()));
                }
            }
        });
    }

}